package cn.tianjindong.blog_portal.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import cn.tianjindong.blog.common.pojo.PageView;
import cn.tianjindong.blog.pojo.BlogArticle;
import cn.tianjindong.blog.pojo.BlogArticleCategory;
import cn.tianjindong.blog_portal.service.CategoryService;

@Controller
public class CategoryController {

	@Autowired
	private CategoryService categoryService;

	/**
	 * 处理Ajax请求,返回所有分类
	 * 
	 * @return
	 */
	@RequestMapping("/category/index-list.action")
	public @ResponseBody String categoryList() {
		List<BlogArticleCategory> list = categoryService.getCategoryList();
		return JSON.toJSONString(list);
	}

	/**
	 * 前往具体的分类页面，显示该分类中的所有文章
	 * 
	 * @param alias
	 * @return
	 */
	@RequestMapping("/category/{alias}.html")
	public String toCategoryPage(Model model, @PathVariable String alias,
			@RequestParam(defaultValue = "1") Integer currentPage,
			@RequestParam(defaultValue = "10") Integer countItem) {
		String categoryName = categoryService.getCategoryNameByAlias(alias);
		if (categoryName == null) {
			return "/404";
		}
		PageView<BlogArticle> pageView = categoryService.getArticlePageViewByCategory(currentPage, countItem, alias);
		model.addAttribute("categoryName", categoryName);
		model.addAttribute("pageView", pageView);
		return "/category";
	}
}
